#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>

pthread_mutex_t lock;

void* fun(void*);

int main(int argc,char** argv)
{
  pthread_mutex_init(&lock,NULL);

  pthread_t tid;
  pthread_create(&tid,NULL,fun,NULL);
  srand(time(NULL));
  int ret;
  while(1)
  {
    ret = pthread_mutex_trylock(&lock);
    if(ret == 0)
    {
      printf("hello ");
      sleep(rand()%2);
      printf("world\n");
      pthread_mutex_unlock(&lock);
      sleep(rand()%2);
    }
  }

  pthread_exit((void*)0);
}


void* fun(void* num)
{
  srand(time(NULL));
  int ret;
  while(1)
  {
    ret = pthread_mutex_trylock(&lock);
    if(ret == 0)
    {
      printf("HELLO ");
      sleep(rand()%3);
      printf("WORLD\n");
      pthread_mutex_unlock(&lock);
      sleep(rand()%3);
    }
  }
}
